#include "list.h"

static ListNode* createNode(dataType x)
{
	ListNode* node = malloc(sizeof (ListNode));
	node->data = x;
	return node;
}

void initList(ListNode* plist)
{
	plist->prev = plist;
	plist->next = plist;
}

void printList(ListNode* plist)
{
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void listPushBack(ListNode* plist, dataType x)
{
	assert(plist != NULL);
	listInsertBefore(plist, x);
}

void listPushFront(ListNode* plist, dataType x)
{
	assert(plist != NULL);
	listInsertAfter(plist, x);
}

void listPopBack(ListNode* plist)
{
	assert(plist != NULL);
	assert(plist->next != plist);
	ListNode* tail = plist->prev;
	ListNode* tailPrev = tail->prev;
	tailPrev->next = plist;
	plist->prev = tailPrev;
	free(tail);
}

void listPopFront(ListNode* plist)
{
	assert(plist != NULL);
	assert(plist->next != plist);
	ListNode* first = plist->next;
	ListNode* second = first->next;
	plist->next = second;
	second->prev = plist;
	free(first);
}

ListNode* findNode(ListNode* plist, dataType x)
{
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void listInsertAfter(ListNode* pos, dataType x)
{
	assert(pos != NULL);
	ListNode* node = createNode(x);
	node->next = pos->next;
	pos->next->prev = node;
	pos->next = node;
	node->prev = pos;
}

void listInsertBefore(ListNode* pos, dataType x)
{
	assert(pos != NULL);
	ListNode* node = createNode(x);
	pos->prev->next = node;
	node->prev = pos->prev;
	node->next = pos;
	pos->prev = node;
}

void listErase(ListNode* pos)
{
	assert(pos != NULL);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}

void destroyList(ListNode* plist)
{
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(plist);
}